package com.you.redisqueue.consumer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Author: weiwei.you
 * @Date: 2020-11-13 19:51
 */

@Component
@Slf4j
public class RedisConsumer {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public Object getData(String key){
        Object result = null;
        if(StringUtils.isEmpty(key)){
            return null;
        }
        try{
            result = redisTemplate.opsForList().rightPop(key);
        } catch (Exception e){
            log.error("redis 获取数据异常",e);
        }

        return result;
    }

    public List<Object> getAllData(String key){
        List<Object> result = null;

        if(StringUtils.isEmpty(key)){
            return null;
        }
        try{
            // 获取队列全部数据
            result = redisTemplate.opsForList().range(key,0,-1);
            if (CollectionUtils.isEmpty(result)) {
                return null;
            }
            // 清空队列
            redisTemplate.opsForList().trim(key,-1,0);
        } catch (Exception e){
            log.error("redis 获取数据异常",e);
        }

        return result;
    }

}
